package com.example.aircraftwar.scorelist;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.aircraftwar.R;
import com.example.aircraftwar.application.MainActivity;
import com.example.aircraftwar.application.game.EasyGame;
import com.example.aircraftwar.application.game.Game;
import com.example.aircraftwar.application.game.GameActivity;
import com.example.aircraftwar.application.game.HardGame;
import com.example.aircraftwar.application.game.NormalGame;
import com.example.aircraftwar.application.loginorregister.LoginOrRegisterActivity;
import com.example.aircraftwar.application.network.NetConn;
import com.example.aircraftwar.startgame.StartGameActivity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class ScoreRankActivity extends AppCompatActivity {

    private TextView patternText;
    private TableLayout tableLayout;
    private SimpleAdapter simpleAdapter;
    private Button deleteButton;
    private static Object[][] tableData;
    private String[] columnName = {"名次","玩家名","得分","记录时间"};
    private String playerName;
    public static ScoreDao scoreDao;
    private Score score;
    private TableRow headerTableRow;
    private TableRow lastTableRow;
    private List<Score> onlineScore;
    private Score score1;
    private Score score2;
    private Handler updatehandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        checkPermission();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_rank);
        patternText = findViewById(R.id.pattern);
        tableLayout = findViewById(R.id.tablelayout);
        deleteButton = findViewById(R.id.delete);
        updatehandler = new updatehandler();

        score = null;

        lastTableRow = new TableRow(this);
        headerTableRow = new TableRow(this);
        for (int i = 0;i < 4;i++) {
            TextView textView = new TextView(this);
            textView.setText(columnName[i]);
            textView.setTextSize(18f);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(getResources().getColor(R.color.red));
            headerTableRow.addView(textView);
        }
        tableLayout.addView(headerTableRow);
        tableLayout.setStretchAllColumns(true);

        try {
            scoreDao = new ScoreDaoImpl(ScoreRankActivity.this);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (MainActivity.isonline) {
//            new Thread(ready).start();
            onlineScore = new ArrayList<>();
            score1 = new Score(1,LoginOrRegisterActivity.userName,Game.score,this.setTime());
            TextView title = findViewById(R.id.title);
            title.setText("双人对战排行榜");
            if (score1.getScore() >= GameActivity.enemy.getScore()) {
                score1.setRank(1);
                GameActivity.enemy.setRank(2);
                ScoreDaoImpl.scores.add(score1);
                ScoreDaoImpl.scores.add(GameActivity.enemy);
            } else {
                score1.setRank(2);
                GameActivity.enemy.setRank(1);
                ScoreDaoImpl.scores.add(GameActivity.enemy);
                ScoreDaoImpl.scores.add(score1);
            }
            update();
        } else {
            showInputDialog();
        }

        if (StartGameActivity.selectPattern == 1) {
            patternText.setText(R.string.easy);
        } else if (StartGameActivity.selectPattern == 2) {
            patternText.setText(R.string.normal);
        } else {
            patternText.setText(R.string.hard);
        }
    }

    Runnable ready = () -> {
        String reply;
        String msg = "";
        String username = LoginOrRegisterActivity.userName;
        try {
            while (!msg.equals("over") && Objects.equals(username, LoginOrRegisterActivity.userName)) {
                while ((reply = NetConn.reader.readLine()) != null) {
                    JSONObject jsonObject = JSONObject.fromObject(reply);
//                    System.out.println("222222222222222222");
//                    System.out.println(reply);
//                    System.out.println(ScoreDaoImpl.scores.size());
//                    System.out.println("222222222222222222");
                    username = jsonObject.getString("username");
                    int score = jsonObject.getInt("score");
                    msg = jsonObject.getString("msg");
                    if (msg.equals("over")) {
                        if (!Objects.equals(username, LoginOrRegisterActivity.userName)) {
                            score2 = new Score(username,GameActivity.enemyScore,this.setTime());
                            if (score >= Game.playscore) {
                                score2.setRank(1);
                                score1.setRank(2);
                                ScoreDaoImpl.scores.add(0,score2);
                            } else {
                                score2.setRank(2);
                                ScoreDaoImpl.scores.add(score2);
                            }
                            System.out.println("222222222222222222");
                            System.out.println(reply);
                            System.out.println(ScoreDaoImpl.scores.size());
                            System.out.println("222222222222222222");
                            Message update = Message.obtain();
                            update.what = 1;
                            updatehandler.sendMessage(update);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    public String setTime(){
        Date time = new Date();
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm:ss");
        String currentTime = format.format(time);
        return currentTime;
    }

        private void showInputDialog() {
        /*@setView 装入一个EditView
         */
        final EditText editText = new EditText(this);
        AlertDialog.Builder inputDialog = new AlertDialog.Builder(this);
        inputDialog.setTitle("游戏结束，您的得分为" + Game.score + "\n请输入名字记录得分！").setView(editText);
        inputDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                playerName =  editText.getText().toString();
                if (playerName.equals("")) {
                    Toast.makeText(ScoreRankActivity.this, "玩家名为空", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ScoreRankActivity.this, "玩家名：" + playerName, Toast.LENGTH_SHORT).show();
                }
                if (playerName != null) {
                    try {
                        scoreDao.scoreadd(playerName, Game.playscore);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    update();
                }
                try {
                    scoreDao.getscorelist();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        inputDialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                playerName = null;
                dialogInterface.dismiss();
            }
        }).show();

        deleteButton.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {// row is your row, the parent of the clicked button
                if (score == null) {
                    Toast.makeText(ScoreRankActivity.this, "请点击要删除的记录", Toast.LENGTH_SHORT).show();
                } else {
                    delete();
                }
            }
        });
    }

    private void delete() {
        AlertDialog.Builder bld = new AlertDialog.Builder(this);
        bld.setMessage("您是否确定删除此记录？");
        bld.setTitle("温馨提示：");
        bld.setPositiveButton("确认", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int swich) {
                // TODO Auto-generated method stub
                try {
                    scoreDao.delete(score.getRank() - 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                tableLayout.removeAllViews();
                tableLayout.addView(headerTableRow);
                update();
                score = null;
                Toast.makeText(ScoreRankActivity.this, "记录已删除", Toast.LENGTH_SHORT).show();
            }
        });
        bld.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int swich) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        bld.create().show();
    }


    public void update() {
        if (ScoreDaoImpl.scores.size() > 0) {
            for (Score player : ScoreDaoImpl.scores) {
                TableRow tableRow = new TableRow(this);
                TextView textView1 = new TextView(this);
                textView1.setText(String.format("%s",player.getRank()));
                textView1.setGravity(Gravity.CENTER);
                textView1.setTextSize(18f);
                tableRow.addView(textView1);
                TextView textView2 = new TextView(this);
                textView2.setText(player.getUserName());
                textView2.setTextSize(18f);
                textView2.setGravity(Gravity.CENTER);
                tableRow.addView(textView2);
                TextView textView3 = new TextView(this);
                textView3.setText(String.format("%s",player.getScore()));
                textView3.setTextSize(18f);
                textView3.setGravity(Gravity.CENTER);
                tableRow.addView(textView3);
                TextView textView4 = new TextView(this);
                textView4.setText(player.getTime());
                textView4.setTextSize(18f);
                textView4.setGravity(Gravity.CENTER);
                tableRow.addView(textView4);
                tableLayout.addView(tableRow);
                tableRow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        score = player;
                        tableRow.setBackgroundColor(getResources().getColor(R.color.color_dark_grey));
                        if (lastTableRow != tableRow) {
                            lastTableRow.setBackgroundColor(getResources().getColor(R.color.white));
                            lastTableRow = tableRow;
                        }
                    }
                });
            }
            tableLayout.setStretchAllColumns(true);
        }
    }

    private String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private List<String> mPermissionList = new ArrayList<>();

    // private ImageView welcomeImg = null;
    private static final int PERMISSION_REQUEST = 1;
    // 检查权限

    private void checkPermission() {
        mPermissionList.clear();

        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了

        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST);
        }
    }

    class updatehandler extends Handler {

        // 通过复写handlerMessage() 从而确定更新UI的操作
        @Override
        public void handleMessage(Message msg) {
            // 根据不同线程发送过来的消息，执行不同的UI操作
            // 根据 Message对象的what属性 标识不同的消息
            switch (msg.what) {
                case 1:
                    tableLayout.removeAllViews();
                    tableLayout.addView(headerTableRow);
                    update();
                    break;
            }
        }
    }

    /**
     * 响应授权
     * 这里不管用户是否拒绝，都进入首页，不再重复申请权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //exit();
            Intent intent = new Intent(ScoreRankActivity.this, StartGameActivity.class);
            startActivity(intent);
            return false;
        }
        else {
            return super.onKeyDown(keyCode, event);
        }
    }

}